package cn.kerui.auth.event;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.kerui.common.framework.util.lang.AddressUtil;
import cn.kerui.common.framework.util.lang.ServletUtil;
import cn.kerui.common.framework.util.lang.StringUtil;
import cn.kerui.auth.event.vo.LoginInfoEvent;
import cn.kerui.repos.entities.log.UserLoginLog;
import cn.kerui.repos.mapper.log.UserLoginLogMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * <p> 异步日志监听处理器 </p>
 * <p>创建于 2024/1/4 12:15 </p>
 *
 * @author yangkai
 * @version v1.0
 * @since 1.0.0
 */
@Component
@Slf4j
public class LogEventListener {

    @Autowired
    private UserLoginLogMapper userLoginLogMapper;


    /**
     * 异步保存登录日志
     *
     * @param loginInfoEvent 登录日志事件请求体
     */
    @Async
    @EventListener
    public void saveLoginLog(LoginInfoEvent loginInfoEvent) {
        HttpServletRequest httpServletRequest = loginInfoEvent.getHttpServletRequest();
        // 获取User-Agent信息对象
        UserAgent userAgent = UserAgentUtil.parse(httpServletRequest.getHeader("User-Agent"));
        // 获取客户端Ip
        String clientIP = ServletUtil.getClientIP(httpServletRequest);

        // 打印登录信息
        StringBuilder s = new StringBuilder();
        s.append(clientIP)
                .append(StringUtil.DASHED)
                .append(loginInfoEvent.getUserName())
                .append(loginInfoEvent.getStatus())
                .append(loginInfoEvent.getMessage());

        log.info(s.toString(), loginInfoEvent.getArgs());

        String address = AddressUtil.getRealAddressByIP(clientIP);
        // 获取客户端操作系统和客户端浏览器
        String os = userAgent.getOs().getName();
        String browser = userAgent.getBrowser().getName();
        // 封装保存对象
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setUserName(loginInfoEvent.getUserName());
        userLoginLog.setDeviceType(loginInfoEvent.getDeviceType());
        userLoginLog.setGrantType(loginInfoEvent.getGrantType());
        userLoginLog.setIpaddr(clientIP);
        // TODO 保存登录地点
        userLoginLog.setLoginLocaltion(address);
        userLoginLog.setOs(os);
        userLoginLog.setBrowser(browser);
        userLoginLog.setMsg(loginInfoEvent.getMessage());
        userLoginLog.setStatus(loginInfoEvent.getStatus());

        userLoginLogMapper.insert(userLoginLog);
    }
}
